package com.pms.web;
import com.pms.controller.BaseController;
import com.pms.exception.R;
import com.pms.exception.RRException;
import com.pms.util.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import sun.misc.BASE64Decoder;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.List;

/**
 * 文件上传控制器
 * 
ss */
@RestController
@Api(value = "图片上传",description = "图片上传")
@RequestMapping(value = "/api/upload")
public class UploadController extends BaseController {
    protected Logger logger = LoggerFactory.getLogger(getClass());

    @Value(value = "${ckeditor.storage.image.path}")
    private String ckeditorStorageImagePath;

    @Value(value = "${ckeditor.access.image.url}")
    private String ckeditorAccessImageUrl;

    OSSClientUtil ossClient = new OSSClientUtil();
    // 上传文件(支持批量)
    String reUrl = "http://upimg.ahmkj.cn";
    // 文件存储目录
    String filedir = "/pms/";


    // 上传文件(支持批量)
    @PostMapping("/imageData")
    @ApiOperation("图片上传")
    @ApiImplicitParams({})
    public Object uploadImageData(HttpServletRequest request, HttpServletResponse response, ModelMap modelMap) {
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setContentType("text/html;charset=utf-8");
        List<String> fileNames = InstanceUtil.newArrayList();
        List<String> urls = InstanceUtil.newArrayList();
        String[] fileDatas = request.getParameterValues("fileData");
        if(null==fileDatas||fileDatas.length<1){
            return R.error("请选择上传的文件");
        }
        for (int i = 0; i < fileDatas.length; i++) {
            String fileStr = fileDatas[i];
            if (fileStr != null && !"".equals(fileStr)) {
                int index = fileStr.indexOf("base64");
                if (index > 0) {
                    try {
                        String fileName = NumberUtil.getNu(NuType.img);
                        String preStr = fileStr.substring(0, index + 7);
                        String prefix = preStr.substring(preStr.indexOf("/") + 1, preStr.indexOf(";")).toLowerCase();
                        fileStr = fileStr.substring(fileStr.indexOf(",") + 1);
                        String pathDir = UploadUtil.getUploadDir(request);
                        BASE64Decoder decoder = new BASE64Decoder();
                        byte[] bb = decoder.decodeBuffer(fileStr);
                        for (int j = 0; j < bb.length; ++j) {
                            if (bb[j] < 0) {// 调整异常数据

                                bb[j] += 256;
                            }
                        }
                        File dir = new File(pathDir);
                        if (!dir.exists()) {
                            dir.mkdirs();
                        }
                        InputStream sbs = new ByteArrayInputStream(bb);
                        String fname = fileName + "." + prefix;
                        String name = ossClient.uploadFile2OSS(sbs, fname);
                        String url = reUrl + "/pms/" + fname;
                        fileNames.add(url);
                        urls.add(url);
                        return  url;
                    } catch (Exception e) {
                        logger.error("上传文件异常：", e);
                    }
                } else {
                    modelMap.put("msg", "请选择要上传的文件！");
                    return modelMap;
                }
            }
        }
        return null;
    }

//    /**
//     * 图片上传
//     * @param file
//     * @param request
//     * @param response
//     * @param modelMap
//     * @return
//     */
//    @RequestMapping(value = "/image", method = RequestMethod.POST)
//      public Object uploadImage(@RequestParam("upload") MultipartFile file, HttpServletRequest request,
//                                HttpServletResponse response, ModelMap modelMap) {
//        String name = "";
//        if (!file.isEmpty()) {
//            try {
//                response.setContentType("text/html; charset=UTF-8");
//                response.setHeader("Cache-Control", "no-cache");
//                //解决跨域问题
//                response.setHeader("X-Frame-Options", "SAMEORIGIN");
//                 PrintWriter out = response.getWriter();
//
//
//                String fileName = NumberUtil.getNu(NuType.img);
//                String pathDir = UploadUtil.getUploadDir(request);
//                byte[] bb = file.getBytes();
//                for (int j = 0; j < bb.length; ++j) {
//                    if (bb[j] < 0) {// 调整异常数据
//
//                        bb[j] += 256;
//                    }
//                }
//                File dir = new File(pathDir);
//                if (!dir.exists()) {
//                    dir.mkdirs();
//                }
//                InputStream sbs = new ByteArrayInputStream(bb);
//                String fname = file.getOriginalFilename();
//                fname = fileName + fname.substring(fname.lastIndexOf("."),fname.length());
//                name = ossClient.uploadFile2OSS(sbs, fname);
//                String url = reUrl + "/fcp/" + fname;
//                // 将上传的图片的url返回给ckeditor
//                String callback = request.getParameter("CKEditorFuncNum");
//                String script = "<script type=\"text/javascript\">window.parent.CKEDITOR.tools.callFunction(" + callback + ", '" + url + "');</script>";
//                out.println(script);
//                out.flush();
//                out.close();
//                return url;
//            } catch (Exception e) {
//                logger.error("上传文件异常：", e);
//            }
//        }else {
//            modelMap.put("msg", "请选择要上传的文件！");
//            return modelMap;
//        }
//     return null;
//    }

    /**
     * 图片上传
     * @param file
     * @param request
     * @param type  1.等比压缩 2.尺寸压缩
     * @return
     * @throws IllegalStateException
     * @throws IOException
     */
    @ApiOperation("图片压缩上传1.等比压缩 2.尺寸压缩")
    @ApiImplicitParams({})
    @PostMapping(value = "/photoUpload")
    public Object photoUpload(MultipartFile file, HttpServletRequest request, Integer type, Integer width, Integer height) throws IllegalStateException, IOException{
        if (type==null){  throw new RRException("压缩类型为空");}
        if (file!=null) {
            if (file.getSize()>=3145728){throw new RRException("上传图片不能超过3M");}
            List<String> fileNames = InstanceUtil.newArrayList();
            List<String> urls = InstanceUtil.newArrayList();
            String path=null;
            String style=null;
            String fileName=file.getOriginalFilename();// 文件原名称
            // 判断文件类型
            style=fileName.indexOf(".")!=-1?fileName.substring(fileName.lastIndexOf(".")+1, fileName.length()):null;
            if (style!=null) {// 判断文件类型是否为空
                if ("GIF".equals(style.toUpperCase())||"PNG".equals(style.toUpperCase())||"JPG".equals(style.toUpperCase())) {
                    // 项目在容器中实际发布运行的根路径
                    String realPath=request.getSession().getServletContext().getRealPath("/");
                    InputStream in = file.getInputStream();
                    byte[] bb = toByteArray(in);
                    for (int j = 0; j < bb.length; ++j) {
                        if (bb[j] < 0) {// 调整异常数据
                            bb[j] += 256;
                        }
                    }
                    byte[] newImage = new byte[0];
                    if (type==1){//等比压缩
                        float proportion=ImgUtil.quality(file.getSize());
                        newImage= ImgUtil.compressPicByQuality(bb, proportion);
                    }else if (type==2){//尺寸压缩
                        if (width== null){throw new RRException("宽度不能为空");}
                        if (height== null){throw new RRException("高度不能为空");}
                        newImage= ImgUtil.compressPic(bb,width,height,true);
                    }
                    if(null==newImage){throw new RRException("图片压缩类型出错，请检查");}
                    for (int j = 0; j < newImage.length; ++j) {
                        if (newImage[j] < 0) {// 调整异常数据
                            newImage[j] += 256;
                        }
                    }
                    InputStream sbs = new ByteArrayInputStream(newImage);
                    String trueFileName = NumberUtil.getNu(NuType.img);
                    String prefix = fileName.substring(fileName.lastIndexOf(".") + 1);
                    String fname = trueFileName + "." + prefix;
                    String name = ossClient.uploadFile2OSS(sbs, fname);
                    String url = reUrl + filedir + fname;
                    fileNames.add(url);
                    urls.add(url);
                    System.out.println(url+"压缩后的图片路径");
                    return url;
                }else {
                    System.out.println("不是我们想要的文件类型,请按要求重新上传");
                    return null;
                }
            }else {
                System.out.println("文件类型为空");
                return null;
            }
        }else {
            System.out.println("没有找到相对应的文件");
            return null;
        }
    }


    /**
     * 流转byte
     * @param in
     * @return
     * @throws IOException
     */
    private byte[] toByteArray(InputStream in) throws IOException {

        ByteArrayOutputStream out = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024 * 4];
        int n = 0;
        while ((n = in.read(buffer)) != -1) {
            out.write(buffer, 0, n);
        }
        return out.toByteArray();
    }
}


